package com.orange.off.cloud.cloudoff.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnItemLongClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.reflect.TypeToken;
import com.orange.off.cloud.cloudoff.R;
import com.orange.off.cloud.cloudoff.adapters.Client_Add_ChoiceListAdapter;
import com.orange.off.cloud.cloudoff.app.MyApplication;
import com.orange.off.cloud.cloudoff.events.Client_Add_ChoiceEvent;
import com.orange.off.cloud.cloudoff.model.Client_Add_Choice_ListBean;
import com.orange.off.cloud.cloudoff.model.UploadResponse;
import com.orange.off.cloud.cloudoff.urls.AppUrls;
import com.orange.off.cloud.cloudoff.utils.GsonUtils;
import com.orange.off.cloud.cloudoff.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

/**
 * 我的客户-推荐客户---选择楼盘
 *
 * @author smile
 */
public class Client_Add_ChoiceFragment extends Fragment {


    @Bind(R.id.common_back)
    RelativeLayout commonBack;
    @Bind(R.id.client_add_choice_btn)
    Button clientAddChoiceBtn;


    /**
     * 服务器端一共多少条数据
     * <p/>
     * 注：如果服务器没有返回总数据或者总页数，这里设置为最大值比如10000，什么时候没有数据了根据接口返回判断
     */
    private static final int TOTAL_COUNTER = 1000;
    /**
     * 每一页展示多少条数据
     */
    private static final int REQUEST_COUNT = 10;
    /**
     * 已经获取到多少条数据了
     */
    private static int mCurrentCounter = 0;
    private LRecyclerView mRecyclerView = null;
    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;


    private Client_Add_ChoiceListAdapter mDataAdapter;

    public static Client_Add_ChoiceFragment newInstance() {
        Client_Add_ChoiceFragment fragment = new Client_Add_ChoiceFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.client_add_choice_fragment, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    private void initViews() {
        mRecyclerView = (LRecyclerView) getActivity().findViewById(R.id.client_add_choice_recyclerView);
        mDataAdapter = new Client_Add_ChoiceListAdapter(getActivity());
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mRecyclerView.setAdapter(mLRecyclerViewAdapter);
        DividerDecoration divider = new DividerDecoration.Builder(getActivity()).setHeight(R.dimen.default_divider_height)
                //                .setPadding(R.dimen.default_divider_padding)
                .setColorResource(R.color.grey).build();

        //        mRecyclerView.addItemDecoration(divider);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        //add a HeaderView
        //        final View header = LayoutInflater.from(getActivity()).inflate(R.layout.sample_header,
        //                (ViewGroup) getActivity().findViewById(android.R.id.content), false);
        //        mLRecyclerViewAdapter.addHeaderView(header);

        mRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrentCounter = 0;
                getListData();

            }
        });

        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能
        mRecyclerView.setLoadMoreEnabled(false);

        mRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {

                if (mCurrentCounter < TOTAL_COUNTER) {
                    // loading more
                    getListData();
                } else {
                    //the end
                    mRecyclerView.setNoMore(true);
                }
            }
        });

        mRecyclerView.setLScrollListener(new LRecyclerView.LScrollListener() {

            @Override
            public void onScrollUp() {
            }

            @Override
            public void onScrollDown() {
                //                ToastUtils.show(getActivity(),"到底了");
            }


            @Override
            public void onScrolled(int distanceX, int distanceY) {
            }

            @Override
            public void onScrollStateChanged(int state) {

            }

        });

        //设置头部加载颜色
        mRecyclerView.setHeaderViewColor(R.color.colorAccent, R.color.dark, android.R.color.white);
        //设置底部加载颜色
        mRecyclerView.setFooterViewColor(R.color.colorAccent, R.color.dark, android.R.color.white);
        //设置底部加载文字提示
        mRecyclerView.setFooterViewHint("拼命加载中", "已经全部为你呈现了", "网络不给力啊，点击再试一次吧");

        mRecyclerView.refresh();

        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mDataAdapter.getDataList().size() > position) {
                    Client_Add_Choice_ListBean item = mDataAdapter.getDataList().get(position);
                    EventBus.getDefault().post(new Client_Add_ChoiceEvent(item.name, item.id,item.url));
                    getActivity().finish();
                }

            }

        });

        mLRecyclerViewAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
                //                Client_Recording_ListBean item = mDataAdapter.getDataList().get(position);
                //                ToastUtils.show(getActivity(), "onItemLongClick - " + item.name);
            }
        });

    }

    @OnClick({R.id.common_back, R.id.client_add_choice_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                getActivity().finish();
                break;
            case R.id.client_add_choice_btn:

                break;
        }
    }

    /**
     * 报备楼盘列表
     */
    void getListData() {
        RequestParams params = new RequestParams();
        params.addFormDataPart("aid", MyApplication.aid);
        params.addFormDataPart("type", "baobei");
        Log.d(MyApplication.DEBUG, "Client_Add_ChoiceFragment---》" + AppUrls.Reported + "--type-->" + "baobei");
        HttpRequest.post(AppUrls.Reported, params, new BaseHttpRequestCallback<UploadResponse>() {
            @Override
            public void onSuccess(UploadResponse uploadResponse) {
                super.onSuccess(uploadResponse);
                Log.d(MyApplication.DEBUG, "Client_Add_ChoiceFragment--success-》" + uploadResponse.toString());
                if (uploadResponse.getSuccess()) {
                    try {
                        Type type = new TypeToken<ArrayList<Client_Add_Choice_ListBean>>() {
                        }.getType();
                        List<Client_Add_Choice_ListBean> list = GsonUtils.getList(uploadResponse.getData(), type);
                        if (list.size() <= 0) {
                            ToastUtils.show(getActivity(), "暂无已认证楼盘项目，请先认证！");
                        }
                        mDataAdapter.setDataList(list);
                        mCurrentCounter += list.size();
                        mRecyclerView.refreshComplete(REQUEST_COUNT);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                } else {
                    ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                }

            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onProgress(int progress, long networkSpeed, boolean done) {
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            getActivity().finish();
            return true;
        }
        return false;
    }


}
